import React, { Component } from 'react';
import {
	View, Text, StyleSheet, TouchableOpacity, Image, TextInput,
	PixelRatio, Platform, ScrollView, Modal, FlatList, Alert, DeviceEventEmitter
} from 'react-native';
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import HTTP from '../../../utils/http';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { API, API_GENERATE } from '../../../config/api';

const scale = GLOBAL.SCALE;

export default class ProductSelect extends Component {

	/* 
	属性： 
		modalVisible:显示,
		single:单选 'true' 单选   'false' 多选, 字符串
		sendData:{companyId:'',companyName:''}
		mainCheckData:[{goodsId:'',goodsName:''}]  //数据回显
	方法：
		cancelPress()   取消按钮回调
		confirmPress()  确定按钮回调
	*/

	constructor(props) {
		super(props);
		console.log(' this.props', this.props)
		let { modalVisible, mainCheckData, single, isZXY, tCode, groupOnoff, isGP } = this.props;
		single = single ? (single == 'true' ? true : false) : true;
		this.state = {
			modalVisible: modalVisible || false,
			sideDataSource: [], // 一级数据
			mainDataSource: [], // 二级数据
			sideCheckData: [], // 一级数据回显
			mainCheckData: mainCheckData || [],   // 二级数据回显
			status: 'loading',  // 数据加载状态
			single,
		}
		this.isZXY = !!isZXY;
		this.tCode = tCode || null;
		this.sendData = this.props.sendData;  //商品参数
		this.goodsState = this.props.sendData.goodsState || '';
		this.goodsStateList = this.props.sendData.goodsStateList || [];
		this.groupOnoff = groupOnoff || null;
		this.isGP = isGP;
	}

	componentWillMount() {
		this._init();
	}

	// 初始  获取数据 且初始化
	_init = async () => {
		//获取数据
		let goodsData = await this._getGoodsData();
		//根据数据初始化
		this._formattingData(goodsData);
	}

	componentWillReceiveProps(props) {
		let { modalVisible, sendData, salesRuleId } = props;
		if (salesRuleId) {
			this.sendData = sendData
		}
		DeviceEventEmitter.addListener('clear', (message) => {
			if (message) {
				this.setState({
					mainCheckData: []
				})
			}
		}
		)
		this.setState({
			modalVisible
		}, () => {
			this._init();
		})
	}

	// 获取商品数据
	_getGoodsData = async () => {
		if (this.sendData.goodsName == '') {
			delete this.sendData.goodsName;
		}
		//过滤产其他产品组的商品
		if (this.groupOnoff) {
			this.sendData.bizTeamId = this.groupOnoff;
		}
		let url = '';
		if (this.tCode && (this.tCode == 'E' || this.tCode == 'QH')) {
			url = API.LONG_FRAME_GOODS_LIST
		} else if (this.isGP) {
			url = API.GET_GP_GOODSLIST;
		} else {
			url = this.isZXY ? API.GET_ZXY_GOODSLIST : API.GET_GOODSLIST
		}
		let responseData = await HTTP.POST(API_GENERATE(url), this.sendData);
		this.setState({
			status: responseData && responseData.length > 0 ? 'data' : 'empty'
		})
		return responseData || [];
	}

	// 数据格式化
	_formattingData = (data, onoff) => {
		let { mainCheckData, sideCheckData, sideDataSource, mainDataSource } = this.state;
		//处理初始化的数据
		mainCheckData = mainCheckData && mainCheckData.filter((item) => {
			if (item.goodsId) {
				return item;
			}
		})
		let indexArr = -1;
		if (mainCheckData.length > 0 && !onoff) {  // 回显
			data && data.map((item, index1) => {
				item.index = 0;    // --------------------
				item.children && item.children.map((items, index2) => {  // 二级
					if (items.goodsId == mainCheckData[0].goodsId) { // 
						items.selected = true;
						indexArr = index1;
						item.index++;  // ---------------
					} else {
						items.selected = false;
					}
					return items
				})
				return item
			})

			data && data.map((item, index1) => {
				if (index1 == indexArr) {
					item.selected = true;
					mainDataSource = item.children;
				} else {
					item.selected = false;
				}
			})
		} else {  // 默认显示第一个
			data && data.map((item, index) => {
				if (index == 0) {
					item.selected = true;
					mainDataSource = item.children;
					sideCheckData.push({ goodsId: item.goodsId, goodsName: item.goodsName });
				} else {
					item.selected = false;
				}
				item.index = 0;    // --------------------
				return item;
			})
		}
		sideDataSource = data;
		this.setState({
			sideDataSource,
			mainDataSource
		})
	}

	// 一级勾选
	_sideCheckFn = (goodsId) => {
		let { sideDataSource, mainDataSource, sideCheckData } = this.state;
		sideDataSource && sideDataSource.map((item) => {
			if (item.goodsId == goodsId) {
				sideCheckData[0] = { goodsId: item.goodsId, goodsName: item.goodsName };
				item.selected = true;
				mainDataSource = item.children;
			} else {
				item.selected = false;
			}
			return item;
		})
		this.setState({
			sideDataSource,
			mainDataSource,
			sideCheckData
		})
	}

	// 二级勾选  [{goodsId:'1',goodsName:'阿三'}]
	_mainCheckFn = (childrenGoodsId, childrenGoodsName, goodsState, isExpired, dangerousType, polyolefinGoodsFlag, isExistPriceFormula, itemId, goodsItem) => {
		let { single, mainCheckData, sideCheckData, sideDataSource } = this.state;
		let isRemove = mainCheckData && mainCheckData.some((item) => {
			return item.goodsId == childrenGoodsId
		})
		let { sendData } = this.props || {};
		let { creditLevel } = sendData || {};

		//企业是一级,选不了二级商品
		if (creditLevel == '1') {
			if (goodsItem.transLevel == 0) {
				Alert.alert('当前企业等级不支持做0级商品!')
				return
			}
		}

		if (isRemove) {  // 移除
			if (single) { // 单选
				mainCheckData = [];
				//sideCheckData = [];
			} else { // 多选
				mainCheckData = mainCheckData && mainCheckData.filter((item) => {
					if (item.goodsId != childrenGoodsId) {
						return item;
					}
				})
			}
		} else {  // 添加
			if (single) { // 单选
				mainCheckData[0] = { goodsId: childrenGoodsId, goodsName: childrenGoodsName, goodsState, isExpired, polyolefinGoodsFlag, isExistPriceFormula, itemId, goodsItem };
			} else { // 多选
				mainCheckData.push({ goodsId: childrenGoodsId, goodsName: childrenGoodsName, goodsState, isExpired, polyolefinGoodsFlag, isExistPriceFormula, itemId, goodsItem });
			}
		}
		if (mainCheckData.length == 0) {
			sideDataSource && sideDataSource.map((item) => {
				item.index = 0;
				item.children && item.children.map((items) => {
					items.selected = false;
					return items;
				})
			})
		} else {
			sideDataSource && sideDataSource.map((item) => {
				item.index = 0;
				item.children && item.children.map((items) => {
					let lsOnoff = mainCheckData && mainCheckData.some((a) => {
						return a.goodsId == items.goodsId
					})
					if (lsOnoff) {
						items.selected = true;
						item.index++;   ///  --------------------------
						return items;
					} else {
						items.selected = false;
						return items;
					}
				})
				return item;
			})
		}
		this.setState({
			sideDataSource,
			mainCheckData,
			//sideCheckData
		})
	}

	//搜索
	_searchFn = () => {
		this.setState({
			mainCheckData: []
		}, async () => {
			//获取数据
			let goodsData = await this._getGoodsData();
			//根据数据初始化
			this._formattingData(goodsData, true);
		})
	}

	// 确定按钮
	_confirmPress = () => {
		let { mainCheckData } = this.state;
		//如果先选择的商品是固体或气体的，后面新增商品选的是液体则需要提示
		if (mainCheckData.length > 0 && mainCheckData[0].goodsState && (mainCheckData[0].goodsState == 'FLUID' || mainCheckData[0].goodsState == 'GAS')) {
			console.log('this.goodsStateList', this.goodsStateList)
			for (i = 0; i < this.goodsStateList.length; i++) {
				if (this.goodsStateList[i] != 'FLUID') {
					Alert.alert('您选择的是液体商品，不能和其它商品放到同一个成交报告中！')
					return
				}
				if (this.goodsStateList[i] != 'GAS') {
					Alert.alert('您选择的是气体商品，不能和其它商品放到同一个成交报告中！')
					return
				}
			}
		}
		if (!this.isZXY && mainCheckData[0] && mainCheckData[0].isExpired == '2') {
			Alert.alert('操作失败，请检查商品交易资质是否过期或缺失！');
			return
		}
		this.setState({
			modalVisible: false
		}, () => {
			this.props.confirmPress && this.props.confirmPress(mainCheckData);
			this.sendData = this.props.sendData;
		})
	}

	// 取消按钮
	_cancelPress = () => {
		let { mainCheckData } = this.state;
		this.setState({
			modalVisible: false
		}, () => {
			this.props.cancelPress && this.props.cancelPress(mainCheckData);
			this.sendData = this.props.sendData;
		})
	}

	// 搜索
	_writeFn = (val) => {
		this.sendData.goodsName = val.replace(/(^\s*)|(\s*$)/g, "");
		this.sendData.searchCode = val.replace(/(^\s*)|(\s*$)/g, "");
	}



	//二级数据
	_renderMain = (data) => {
		const { goodsName, goodsId, selected, goodsState, isExpired, dangerousType, polyolefinGoodsFlag, isExistPriceFormula, itemId, transLevel } = data.item;
		let optionPicSourse = require('../../../imgs/global/option.png');
		let selectedPicSourse = require('../../../imgs/global/success.png');
		let fluidPicSourse = require('../../../imgs/order/fluid.png');
		let dangerousText = '';
		let dangerousTypeText = '';
		let tipsBorderColor = '';
		let { sendData } = this.props || {};
		let { creditLevel } = sendData || {};
		// 判断是否有是危化品
		if (dangerousType && dangerousType != 0) {
			dangerousText = '危';
			switch (dangerousType) {
				case '1':
					dangerousTypeText = ''
					break;
				case '2':
					dangerousTypeText = '毒';
					tipsBorderColor = '#000087';
					break;
				case '3':
					dangerousTypeText = '爆';
					tipsBorderColor = '#FB0007';
					break;
				case '4':
					dangerousTypeText = '燃';
					tipsBorderColor = '#1183FF';
					break;
				case '5':
					dangerousTypeText = '油'
					tipsBorderColor = '#272727';
					break;
				default:
					dangerousTypeText = ''
			}
		}
		let picSource = selected ? selectedPicSourse : optionPicSourse;
		return (
			<TouchableOpacity onPress={() => {
				this._mainCheckFn(goodsId, goodsName, goodsState, isExpired, dangerousType, polyolefinGoodsFlag, isExistPriceFormula, itemId, data.item);
			}} activeOpacity={0.5} style={styles.listMainRow}>
				<View style={{ width: 50 * scale, flexDirection: 'row', justifyContent: 'space-around', alignItems: 'center' }}>
					{
						dangerousText ? <View style={[styles.tips, { borderColor: '#FC8709' }]}><Text style={[styles.tipsText, { color: '#FC8709' }]}>{dangerousText}</Text></View> : null
					}
					{
						dangerousType && dangerousType == '4' ? <Text style={{ fontSize: 12 * scale }}>/</Text> : null
					}
					{
						dangerousTypeText ? <View style={[styles.tips, { borderColor: tipsBorderColor }]}><Text style={[styles.tipsText, { color: tipsBorderColor }]}>{dangerousTypeText}</Text></View> : null
					}
					{
						goodsState == 'FLUID' ? <View style={{ width: 16 * scale, height: 16 * scale }}><Image source={fluidPicSourse} style={{ width: 16 * scale, height: 16 * scale }} /></View> : null
					}
				</View>
				<Text style={[styles.listSideText, styles.longText]}>
					{goodsName}
				</Text>
				{
					(creditLevel == '1' && transLevel == 0) ? <View style={styles.optionPicActive}></View> : <Image source={picSource} style={styles.optionPic} />
				}
			</TouchableOpacity>
		);
	}

	//一级数据
	_renderSide = (side) => {
		let { goodsName, goodsId, children, selected, index } = side.item;
		let curStyle = (selected) ? styles.listSideRowCur : null;
		let { single } = this.state;
		return (
			<TouchableOpacity onPress={() => { this._sideCheckFn(goodsId, children); }} activeOpacity={0.5} style={[styles.listSideRow, curStyle]}>
				<Text style={styles.listSideText}>{goodsName}</Text>
				{
					(index > 0 && !single) ? (< Text style={styles.selectNumber}>{index}</Text>) : null
				}
			</TouchableOpacity >
		);
	}

	render() {
		let { modalVisible, sideDataSource, mainDataSource, status } = this.state;
		return (
			<Modal animationType={"fade"}
				transparent={true}
				onRequestClose={() => { console.log(1) }}
				visible={modalVisible}  >
				<View style={styles.containerModal}>
					<View style={styles.listCell}>
						<View style={styles.listHead}>
							<TouchableOpacity onPress={() => { this._cancelPress() }} activeOpacity={0.5}>
								<Text style={styles.listHeadText}>取消</Text>
							</TouchableOpacity>
							<Text style={[styles.listHeadText, { fontSize: 14 * scale, color: '#404040' }]}>请选择商品</Text>
							<TouchableOpacity onPress={() => { this._confirmPress() }} activeOpacity={0.5}><Text style={styles.listHeadText}>确定</Text>
							</TouchableOpacity>
						</View>
						{
							(this.tCode == 'QH' || this.tCode == 'E') ? (
								<View style={{ paddingLeft: 18 * scale, paddingRight: 18 * scale, paddingBottom: 10 * scale }}>
									<Text style={{ fontSize: 12 * scale, opacity: .8, lineHeight: 18 * scale }}>*商品已根据框架及企业绑定关系进行过滤，若本次交易商品不存在，请维护框架对应的结算公式或检查操作人与企业商品绑定关系。</Text>
								</View>
							) : null
						}
						<View style={styles.searchBox}>
							<TouchableOpacity activeOpacity={1} onPress={() => { this.refs.searchInput.focus() }} style={styles.searchBg}>
								<Image source={require('../../../imgs/customer/searchLeft.png')} style={styles.searchImg} />
								<TextInput
									ref={'searchInput'}
									style={styles.searcuhInput}
									underlineColorAndroid='transparent'
									placeholder={'搜索商品'}
									onChangeText={(value) => {
										this._writeFn(value);
									}}
									onBlur={() => {
										if (this.sendData.goodsName == '') {
											this._init()
										}
									}}
									onSubmitEditing={() => {
										this._searchFn();
									}}
									returnKeyType={'search'}
								/>
							</TouchableOpacity>
							<Text style={styles.searchBtn} onPress={this._searchFn}>搜索</Text>
						</View>
						<View style={styles.listView}>
							{sideDataSource && sideDataSource.length > 0 ? (
								<View style={{ flex: 1, flexDirection: 'row' }}>
									<View style={styles.listSideWrap}>
										<FlatList
											extraData={this.state}
											style={styles.listSideView}
											data={sideDataSource}
											renderItem={this._renderSide}
										/>
									</View>
									<ScrollView
										horizontal={true}
										style={styles.listMainWrap}
									>
										{
											mainDataSource && mainDataSource.length > 0 ? (
												<FlatList
													extraData={this.state}
													style={styles.listMainView}
													data={mainDataSource}
													renderItem={this._renderMain}
												/>
											) : (
												<View style={{ width: 255 * scale }}>
													<PageStatusIndex status={'empty'} emptyText={'该类目暂时无子商品'} />
												</View>
											)
										}
									</ScrollView>
								</View>
							) : (<PageStatusIndex status={status} emptyText={'暂无商品'} />)}
						</View>
					</View>
				</View>
			</Modal>
		);
	}

}


const styles = StyleSheet.create({
	containerModal: {
		width: 375 * scale,
		height: GLOBAL.SCREEN_HEIGHT,
		backgroundColor: 'rgba(0, 0, 0, .3)',
		justifyContent: 'flex-end'
	},
	listHead: {
		flexDirection: 'row',
		justifyContent: 'space-around',
		height: 52 * scale,
		width: 375 * scale,
		alignItems: 'center',
	},
	listHeadText: {
		fontSize: 16 * scale,
		color: style.color.themeColor,
		paddingTop: 5 * scale,
		paddingBottom: 5 * scale,
		paddingLeft: 8 * scale,
		paddingRight: 8 * scale
	},
	listCell: {
		backgroundColor: '#fff',
		width: 375 * scale,
		height: '70%',
	},
	listView: {
		flex: 1,
		flexDirection: 'row',
		borderTopColor: '#e4e4e4',
		borderTopWidth: 1 / PixelRatio.get(),
	},
	listSideWrap: {
		paddingBottom: 20 * scale,
		backgroundColor: '#F8F8F8',
	},
	listSideView: {
		width: 120 * scale,
	},
	listSideRow: {
		height: 50 * scale,
		justifyContent: 'center',
		alignItems: 'center',
		flexDirection: 'row'
	},
	listSideRowCur: {
		backgroundColor: '#fff',
	},
	listSideText: {
		fontSize: 13 * scale,
		color: '#8B8B8B',
	},
	longText: {
		fontSize: 13 * scale,
		color: '#8B8B8B',
		width: 160 * scale
	},
	listMainWrap: {
		paddingBottom: 20 * scale,
		backgroundColor: '#fff',
		width: 255 * scale,
	},
	listMainView: {
		width: 255 * scale,
		paddingLeft: 2 * scale,
		paddingRight: 20 * scale,
		backgroundColor: '#fff'
	},
	listMainRow: {
		alignItems: 'center',
		flexDirection: 'row',
		justifyContent: 'space-between',
		paddingTop: 10 * scale,
		paddingBottom: 10 * scale
	},
	optionPic: {
		width: 14 * scale,
		height: 14 * scale,
		marginRight: 1 * scale
	},
	optionPicActive: {
		width: 14 * scale,
		height: 14 * scale
	},
	searchBox: {
		height: 45 * scale,
		paddingLeft: 15 * scale,
		paddingTop: 8 * scale,
		paddingBottom: 7 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		borderTopColor: '#e4e4e4',
		borderTopWidth: 1 / PixelRatio.get(),
	},
	searchBg: {
		width: 300 * scale,
		height: 30 * scale,
		backgroundColor: style.color.light,
		borderRadius: 4 * scale,
		flexDirection: 'row',
		alignItems: 'center',
	},
	searchBtn: {
		fontSize: 16 * scale,
		color: style.color.dark,
		marginLeft: 10 * scale,
		padding: 5 * scale
	},
	searchImg: {
		width: 12 * scale,
		height: 11 * scale,
		marginLeft: 20 * scale,
		marginRight: 20 * scale
	},
	searcuhInput: {
		width: 200 * scale,
		paddingVertical: 0,
		height: 18 * scale
	},
	selectNumber: {
		borderRadius: 5 * scale,
		width: 20 * scale,
		height: 14 * scale,
		marginLeft: 5 * scale,
		fontSize: 11 * scale,
		backgroundColor: style.color.themeColor,
		color: style.color.white,
		textAlign: 'center'
	},
	tips: {
		width: 15 * scale,
		height: 15 * scale,
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		borderWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderRadius: 2 * scale,

	},
	tipsText: {
		fontSize: 10 * scale
	}
})